﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
using System.Linq;

namespace CqBuiltinService.Controller
{
    public class ModelValidateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            
            if (!context.ModelState.IsValid)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                //获取所有错误的Key
                List<string> Keys = context.ModelState.Keys.ToList();
                //获取每一个key对应的ModelStateDictionary
                foreach (var key in Keys)
                {
                    var errors = context.ModelState[key].Errors.ToList();
                    //将错误描述添加到sb中
                    foreach (var error in errors)
                    {
                        sb.Append(error.ErrorMessage + "| ");
                    }
                }
                context.Result = new BadRequestObjectResult(sb.ToString());
            }

            base.OnActionExecuting(context);
        }
    }
}
